//request请求封装,支持Promise
let request = {
	//baseURL
	baseURL: 'http://www.shop.net/api',
	ajax({ url, data, header, method, ...config }) {
		//完整API接口地址
		url = this.baseURL + url;
		//提取token
		let token = uni.getStorageSync('token');
		//默认headers设置
		let default_headers = {
			'Authori-zation': token,
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url,
				data,
				method,
				header: { ...default_headers, ...header },
				success(res) {
					let { statusCode, header, errMsg, data, cookies } = res;
					//根据状态码statusCode判断
					switch (statusCode) {
						case 200:
							resolve(data);
							break;
						case 401:
							uni.showToast({
								title: `错误码：${statusCode}，登录认证失败！`,
								icon: 'none',
							})
							reject(res);
							break;
						case 404:
							uni.showToast({
								title: `错误码：${statusCode}，API接口地址错误！`,
								icon: 'none',
							})
							reject(res);
							break;
						case 500:
							uni.showToast({
								title: `错误码：${statusCode}，请联系后端程序员！`,
								icon: 'none',
							})
							reject(res);
							break;
						default:
							uni.showToast({
								title: `错误码：${statusCode}，服务器错误`,
								icon: 'none',
							})
							reject(res);
							break;
					}
				},
				...config,
			})
		})
	},
	get(url, data) {
		try {
			return this.ajax({ url, data, method: 'GET' })
		} catch (error) {
			console.log(error);
		}
	},
	post(url, data) {
		try {
			return this.ajax({ url, data, method: 'POST' })
		} catch (error) {
			console.log(error);
		}
	},
	put(url, data) {
		try {
			return this.ajax({ url, data, method: 'PUT' })
		} catch (error) {
			console.log(error);
		}
	},
	delete(url, data) {
		try {
			return this.ajax({ url, data, method: 'DELET' })
		} catch (error) {
			console.log(error);
		}
	},
}

export default request